package com.abapi.pay.service;

import com.abapi.pay.SpringContext;
import com.abapi.pay.core.annotation.AbapiPayCallback;
import com.abapi.pay.core.annotation.EndpointMapping;
import com.abapi.pay.core.biz.Encode;
import com.abapi.pay.core.constans.MessageType;
import com.abapi.pay.core.dto.AliBizDTO;
import com.abapi.pay.core.dto.MessageDTO;
import com.abapi.pay.core.dto.SuccessDTO;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Author ldx
 * @Date 2020/1/31 15:38
 * @Description
 * @Version 1.0.0
 */
@EndpointMapping(value = MessageType.ALI_BIZ,desc = "支付宝回调")
public class AliBizService implements AbstractEndpointService {

    @Override
    public void handler(ChannelHandlerContext context, MessageDTO dto) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
        AliBizDTO aliBizDTO = (AliBizDTO) dto.getBody();
        Map<String,String> map = JSON.parseObject(aliBizDTO.getClassName(),Map.class);
        String className = map.get(aliBizDTO.getMethod());
        Class aClass = Class.forName(className);

        final Object bean = SpringContext.getApplicationContext().getBean(aClass);
        Method[] methods = bean.getClass().getDeclaredMethods();
        Method method = null;
        for(Method m : methods){
            AbapiPayCallback annotation = m.getAnnotation(AbapiPayCallback.class);
            if(annotation == null) {continue;}
            String c = annotation.backName()+"_"+annotation.payType().toString();
            if(c.equals(aliBizDTO.getMethod())){
                method = m;
                break;
            }
        }
        String [] str = new String[]{aliBizDTO.getBackInfo()};
        try {
            method.invoke(bean,str);
        }catch (Exception e){

        }


        MessageDTO messageSuccess = new MessageDTO();
        messageSuccess.setType(MessageType.SUCCESS);
        SuccessDTO successDTO = new SuccessDTO();
        successDTO.setId(aliBizDTO.getId());
        messageSuccess.setBody(successDTO);
        ByteBuf buf = context.channel().alloc().buffer();
        buf.writeBytes(Encode.encode(messageSuccess));
        context.channel().writeAndFlush(buf);
    }
}
